﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace CMS6Tools.Common
{
    public class GenericNameTypeProviderSection<T> : SerializableConfigurationSection, IInstanceFactory<T>
    {
        public const string ObjectsPropertyName = "objects";

        public GenericNameTypeProviderSection()
        {
            Objects = new NameTypeConfigurationElementCollection<GenericNameTypeData<T>, GenericNameTypeData<T>>();
        }

        [ConfigurationProperty(ObjectsPropertyName)]
        public NameTypeConfigurationElementCollection<GenericNameTypeData<T>, GenericNameTypeData<T>> Objects
        {
            get
            {
                return (NameTypeConfigurationElementCollection<GenericNameTypeData<T>, GenericNameTypeData<T>>)this[ObjectsPropertyName];
            }
            set
            {
                this[ObjectsPropertyName] = value;
            }
        }

        public virtual T CreateInstance(string name)
        {
            if (Objects != null)
            {
                var genericNameTypeData = Objects.Get(name);
                if (genericNameTypeData != null)
                    return genericNameTypeData.CreateInstance();
            }
            return default(T);
        }
    }
}
